package com.example.demo.service;

import org.flowable.dmn.api.DmnDecisionService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * DMN代理服务示例：自动决策审批规则
 * 这个服务会根据DMN规则自动决定审批流程
 */
@Component
public class DecisionService implements JavaDelegate {

    @Autowired
    private DmnDecisionService dmnDecisionService;

    @Override
    public void execute(DelegateExecution execution) {
        // 获取流程变量
        String employee = (String) execution.getVariable("employee");
        String reason = (String) execution.getVariable("reason");
        Integer days = (Integer) execution.getVariable("days");
        
        // 模拟员工级别和请假类型（实际应用中从数据库获取）
        String employeeLevel = determineEmployeeLevel(employee);
        String leaveType = determineLeaveType(reason);
        
        // 准备DMN决策输入
        Map<String, Object> decisionInput = new HashMap<>();
        decisionInput.put("employeeLevel", employeeLevel);
        decisionInput.put("days", days);
        decisionInput.put("leaveType", leaveType);
        
        System.out.println("=== DMN代理服务执行 ===");
        System.out.println("员工：" + employee + "，级别：" + employeeLevel);
        System.out.println("请假：" + days + "天，类型：" + leaveType);
        
        try {
            // 执行DMN决策
            var decisionResult = dmnDecisionService.createExecuteDecisionBuilder()
                    .decisionKey("leaveApprovalDecision")
                    .variables(decisionInput)
                    .executeWithSingleResult();
            
            if (decisionResult != null) {
                String approvalResult = (String) decisionResult.get("approvalResult");
                String approverLevel = (String) decisionResult.get("approverLevel");
                Boolean needHRApproval = (Boolean) decisionResult.get("needHRApproval");
                
                System.out.println("DMN决策结果：");
                System.out.println("- 审批结果：" + approvalResult);
                System.out.println("- 审批人级别：" + approverLevel);
                System.out.println("- 需要HR审批：" + needHRApproval);
                
                // 设置流程变量
                execution.setVariable("approvalResult", approvalResult);
                execution.setVariable("approverLevel", approverLevel);
                execution.setVariable("needHRApproval", needHRApproval);
                execution.setVariable("autoApproved", "自动批准".equals(approvalResult));
                
            } else {
                System.out.println("DMN决策未找到匹配规则，使用默认审批流程");
                execution.setVariable("approvalResult", "需要审批");
                execution.setVariable("approverLevel", "直接主管");
                execution.setVariable("needHRApproval", false);
                execution.setVariable("autoApproved", false);
            }
            
        } catch (Exception e) {
            System.err.println("DMN决策执行失败：" + e.getMessage());
            // 设置默认值
            execution.setVariable("approvalResult", "需要审批");
            execution.setVariable("approverLevel", "直接主管");
            execution.setVariable("needHRApproval", false);
            execution.setVariable("autoApproved", false);
        }
        
        System.out.println("========================");
    }
    
    /**
     * 模拟确定员工级别
     */
    private String determineEmployeeLevel(String employee) {
        // 实际应用中从数据库查询员工信息
        if (employee.contains("经理") || employee.contains("Manager")) {
            return "经理";
        } else if (employee.contains("主管") || employee.contains("Lead")) {
            return "主管";
        } else {
            return "普通员工";
        }
    }
    
    /**
     * 模拟确定请假类型
     */
    private String determineLeaveType(String reason) {
        if (reason.contains("病") || reason.contains("医院") || reason.contains("生病")) {
            return "病假";
        } else if (reason.contains("事") || reason.contains("个人")) {
            return "事假";
        } else if (reason.contains("年") || reason.contains("旅游")) {
            return "年假";
        } else {
            return "事假";
        }
    }
}
